package com.lee.demo1.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.mylib.www.MD5Utils;

import com.lee.demo1.business.SysUserBusiness;
import com.lee.demo1.domain.SysUser;

@Controller
public class LoginController {
	
	private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Resource
	private SysUserBusiness sysUserBusiness;
	
	
	
	@RequestMapping("login")
	public String login(){
		return "admin/login";
	}
	
	/**
	 * 退出管理系统
	 * @param request
	 * @return
	 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request){
		request.getSession().removeAttribute("sessionSysUser");
		return "redirect:/login";
	}
	
	/**
	 * 验证用户登录，并更新登录用户时间IP
	 * @param sysUser
	 * @param redirectAttributes
	 * @param request
	 * @return
	 */
	@RequestMapping("doLogin")
	public String doLogin( SysUser sysUser,
			RedirectAttributes redirectAttributes, 
			HttpServletRequest request){
		
		sysUser.setPassword(MD5Utils.getInstance().encrypt(sysUser.getPassword()));
		String request_code = request.getParameter("code");
		String session_code = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		SysUser user = sysUserBusiness.getSysUserByNameAndPassword(sysUser);
		if(null != user){
			if(StringUtils.equals(request_code, session_code)){
				request.getSession().setAttribute("sessionSysUser", user);//session user
				//更新用户登录最后时间和IP
				sysUserBusiness.updateLastLoginTimeAndIP(user.getId(),request.getRemoteHost());
				return "redirect:/frame";
			}else{
				redirectAttributes.addFlashAttribute("name", sysUser.getName());
				redirectAttributes.addFlashAttribute("message", 2); //验证码不正确
				return "redirect:/login";
			}
		}else{
			redirectAttributes.addFlashAttribute("name", sysUser.getName());
			redirectAttributes.addFlashAttribute("message", 1); //用户名或密码不存在
			return "redirect:/login";
		}
	}
	
}
